package id.mankel.commons.logging;

import id.mankel.commons.constants.Asciis;
import id.mankel.commons.crypto.digest.Digests;
import org.slf4j.MDC;

import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author dongxi.li
 */
public class Logs {

    private static final String TRACE_ID = "traceId";

    /**
     * Set at below:
     * <ol>
     *     <li>Web Interceptor</li>
     *     <li>Scheduling Task</li>
     * </ol>
     */
    public static void setTraceId() {
        MDC.put(TRACE_ID, Digests.md5(IntStream.range(0, 10).mapToObj(i -> UUID.randomUUID().toString()).collect(Collectors.joining(Asciis.POUND.s))));
    }

    public static void removeTraceId() {
        MDC.remove(TRACE_ID);
    }

    public static Runnable wrap(Runnable runnable) {
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        return () -> {
            try {
                MDC.setContextMap(contextMap);
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }

}
